
const server = require('http').createServer();
const io = require('socket.io')(server);
let Gobang = require('./lib/gobang');
server.listen(3000,'192.168.99.66');
let gobang = new Gobang();

io.on('connection',function (socket) {
    if(gobang.createPlayer(socket)){

        socket.emit('conn',{
            color:socket.player.color,
            num:gobang.getPlayerNum(),
            hs:gobang.HORIZNTAL_SIZE,
            vs:gobang.VERTICAL_SIZE
        });
        if(gobang.getPlayerNum()>=2){
            gobang.init();
            broadcast()
        }
    }else {
        socket.emit('conn',{
            color:'null',
            num:gobang.getPlayerNum(),
            hs:gobang.HORIZNTAL_SIZE,
            vs:gobang.VERTICAL_SIZE
        });
        broadcast();
    }
    socket.on('disconnect',function () {
        gobang.leftGame(socket)
    });
    socket.on('putchess',function (x,y) {
        x= parseInt(x);
        y= parseInt(y);
        gobang.putChess(x,y);
        broadcast();

        if(gobang.gameover(x,y)){
            io.sockets.emit('gameover',gobang.trun==='black'?'white':'black')
        }
    })
});


function broadcast() {
    io.sockets.emit('getCheckBoard',{
        trun:gobang.trun,
        checkerboard:gobang.checkerBoard
    })
}